package cn.zoujiedev.netty.demo;

import cn.zoujiedev.netty.core.decoder.NettyMessageDecoder;
import cn.zoujiedev.netty.core.encoder.NettyMessageEncoder;
import cn.zoujiedev.netty.core.handler.HeartbeatRespHandler;
import cn.zoujiedev.netty.core.handler.LoginAuthRespHandler;
import cn.zoujiedev.netty.core.serialization.HessianDecoder;
import cn.zoujiedev.netty.core.serialization.HessianEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @Classname Server
 * @Description
 * @Date 2022-11-3 17:04
 * @Created by zoujie
 */
@Slf4j
public class NettyServer {

  private int port;

  public NettyServer(int port){
    this.port = port;
  }

  public void bind() throws Exception{
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.channel(NioServerSocketChannel.class)
        .group(bossGroup,workerGroup)
        .option(ChannelOption.SO_BACKLOG,100)
        .handler(new LoggingHandler(LogLevel.INFO))
        .childHandler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("messageDecoder",new NettyMessageDecoder(1024 * 1024,4,4,new HessianDecoder()));
            ch.pipeline().addLast("messageEncoder",new NettyMessageEncoder(new HessianEncoder()));
            ch.pipeline().addLast("readTimeoutHandler",new ReadTimeoutHandler(50));
            ch.pipeline().addLast("loginResHandler",new LoginAuthRespHandler());
            ch.pipeline().addLast("heartbeatHandler",new HeartbeatRespHandler());
          }
        });

    ChannelFuture sync = bootstrap.bind(port).sync();

    log.info("server start ok");
  }

  public static void main(String[] args) throws Exception {
    new NettyServer(8598).bind();
  }
}
